//
//  AppDelegate.m
//  TMGold
//
//  Created by apple on 2017/11/8.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "AppDelegate.h"
#import "TMGoldTabbarViewController.h"
#import "TMGLoginViewController.h"
#import "TMGGuideViewController.h"
#import "JPUSHService.h"
@interface AppDelegate ()<WXApiDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [SVProgressHUD setMinimumDismissTimeInterval:3];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [TMGoldTabbarViewController new];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //注册微信
    bool success =  [WXApi registerApp:wechatID];
    //注册环信
    [self configIM];
    //配置推送
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         [self configJpush:launchOptions];
    });
   
    NSString * shoed = [[NSUserDefaults standardUserDefaults] valueForKey:isShowGuideKey];
    if (!shoed.length) {
        self.window.rootViewController = [TMGGuideViewController new] ;
         return YES;
    }
    if (![STUserManger defult].token.length) {
        self.window.rootViewController = [[STNavigationController alloc] initWithRootViewController:[TMGLoginViewController new]];
    }




    return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if ([url.description containsString:wechatID]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return nil;
    
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    if ([url.description containsString:wechatID]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
//处理支付宝
- (NSString*)hudFromCode:(NSString*)code{
    if ([code isEqualToString:@"9000"]) {
        return @"支付成功";
    }
    if ([code isEqualToString:@"8000"]) {
        return @"正在处理中";
    }
    if ([code isEqualToString:@"4000"]) {
        return @"订单支付失败";
    }
    if ([code isEqualToString:@"5000"]) {
        return @"重复请求，支付失败";
    }
    if ([code isEqualToString:@"6001"]) {
        return @"中途取消，支付失败";
    }
    if ([code isEqualToString:@"6002"]) {
        return @"网络连接错误";
    }
    if ([code isEqualToString:@"6004"]) {
        return @"支付结果未知";
    }
    return @"未知错误";
}
#pragma mark --WXApiDelegate
- (void)onResp:(BaseResp*)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * loginresp = (SendAuthResp*)resp;
        NSString * token = loginresp.code;
        NSLog(@"%d",loginresp.errCode);
        NSLog(@"%@",token);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信登录"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝了微信登录"];
        }
        if (resp.errCode == 0) {
            // [SVProgressHUD showSuccessWithStatus:@"微信登录成功"];
//            NSString * url =   [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wechatID,wechatSecret,token];
           // [self fetchWeChatOpenIdRequestWithUrl:url];
            // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp * share = (SendMessageToWXResp*)resp;
        NSLog(@"%d",share.errCode);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信分享"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信分享"];
        }
        if (resp.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信分享成功"];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp * pay = (PayResp*)resp;
        NSLog(@"%d",pay.errCode);
        if (pay.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信支付"];
        }
        if (pay.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信支付"];
        }
        if (pay.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信支付成功"];
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
     [[EMClient sharedClient] applicationDidEnterBackground:application];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[EMClient sharedClient] applicationWillEnterForeground:application];
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
     self.registrationID = [JPUSHService registrationID];
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    self.token = token;

}
#pragma mark --Private Method
- (void)configIM{
    EMOptions *options = [EMOptions optionsWithAppkey:IM_appKey];
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    if ([STUserManger defult].loginUser.mobile.length) {
        EMClient * client = [EMClient sharedClient];
        NSString * userName =[STUserManger defult].loginUser.mobile;
        NSString * pwd = @"123456";
        BOOL isSuccess = [client registerWithUsername:userName password:pwd];
        
        
        [client loginWithUsername:userName password:pwd completion:^(NSString *aUsername, EMError *aError) {
            //单聊
            [client.contactManager addContact:@"service_one" message:@"iOS 登录成功自动添加好友"];

            
        }];
    }

}
- (void)configJpush:(id)launchOptions{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    
#ifdef DEBUG
    [JPUSHService setupWithOption:launchOptions
                           appKey:jpushAppKey
                          channel:@"noren"
                 apsForProduction:0];
#else
    [JPUSHService setupWithOption:launchOptions
                           appKey:jpushAppKey
                          channel:@"noren"
                 apsForProduction:1];
#endif
    


}

#pragma mark- JPUSHRegisterDelegate

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
@end
